package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.Utils.DateUtil;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Map<String, Object> paramMap) {
        String jsonString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);

        //根据 医院编号 和 排班编号查询
        Schedule scheduleExist = scheduleRepository.findByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        //判断
        if (scheduleExist != null) {
/*
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setIsDeleted(0);
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
*/
            schedule.setId(schedule.getId());
            schedule.setCreateTime(scheduleExist.getCreateTime());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);

        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> selectPage(int page, int limit, String hoscode) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        PageRequest pageRequest = PageRequest.of(page, limit, sort);

        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        Example<Schedule> example = Example.of(schedule);

        Page<Schedule> pages = scheduleRepository.findAll(example, pageRequest);
        return pages;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.findByHoscodeAndHosScheduleId(hoscode, hosScheduleId);

        if (null != schedule) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * 根据医院编号 和 科室编号 ，查询排班规则（按日期展示）
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        //组装查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //创建聚合对象并添加条件
        Aggregation agg = Aggregation.newAggregation(
                //1 查询条件
                Aggregation.match(criteria),
                //2 按照日期分组 根据workDate分组  select workDate as workDate from schedule group by workDate
                Aggregation.group("workDate").first("workDate").as("workDate")
                        //3 医生人数
                        .count().as("docCount")
                        //4 可预约数
                        .sum("reservedNumber").as("reservedNumber")
                        //5 剩余预约数
                        .sum("availableNumber").as("availableNumber"),
                //6 排序
                Aggregation.sort(Sort.Direction.ASC, "workDate"),
                //7 分页 偏移,每页数量
                Aggregation.skip((page - 1) * limit), Aggregation.limit(limit)
        );

        //执行查询，获取聚合结果  查询Schedule集合，将文档中的同名字段数据存入BookingScheduleRuleVo类
        AggregationResults<BookingScheduleRuleVo> aggregateResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        //分组查询后的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );

        AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //获取查询结果
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregateResults.getMappedResults();

        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            //调用工具类转换显示的日期类型
            String dayOfWeek = DateUtil.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        Map<String, Object> map = new HashMap<>();
        map.put("list", bookingScheduleRuleVoList);
        map.put("total", total);
        return map;
    }

    /**
     * 获取详细时间表
     *
     * @param hoscode
     * @param depcode
     * @param workDate 需要更改格式为Date,使用DateTime工具类
     * @return
     */
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        List<Schedule> list =
                scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());

        return list;
    }
}
